<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/23
 * Time: 11:34
 */

namespace app\index\controller;


use app\index\model\ArticleModel;
use app\index\model\BannerModel;
use app\index\model\MusicModel;
use app\index\model\UserModel;
use think\facade\Cache;
use think\Request;

class Article extends Base
{
    /**
     * 渲染文章
     * @return \think\response\Json
     */
    public function getArticle()
    {
        // 获取所有新闻数据
        $data = ArticleModel::where(['status' => 1])
            ->alias('a')
            ->join('article_info b','a.id = b.article_id')
            ->select();
        foreach ($data as $key => $value) {
            // 时间格式转换
            $data[$key]['date'] = date("M d Y",$value["create_time"]);
            $data[$key]["dateTime"] = ago($value["create_time"]);
        }

        // 获取作者名
        $userData = UserModel::where(['status' => 1])->field('username')->select();
        foreach ($userData as $key => $value) {
            $data[$key]["author"] = $value["username"];
        }

        // 获取音乐数据
        $musicData = MusicModel::where(['status' => 1])->field('title,url,coverImg')->select();
        $data = $this->getMusic($data,$musicData);
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 获取音乐数据
     * @param $data
     * @param $musicData
     * @return mixed
     */
    public function getMusic($data,$musicData)
    {
        foreach ($data as $key => $value) {
            $data[$key]['music'] = $musicData[$key];
        }
        return $data;
    }

    /**
     * 获取轮播图数据
     * @return \think\response\Json
     */
    public function getBanner()
    {
        $data = BannerModel::where(['status' => 1])
            ->select();
        return json(['code' => 1, 'data' => $data]);
    }

    /**
     * 文章收藏次数
     * @param Request $request
     * @return \think\response\Json
     */
    public function addCollected(Request $request)
    {
        if ($id = $request->param("id")) {
            $data = $request->post();

            // 获取当前文章的收藏人数
            $articleData = ArticleModel::where('id',$id)->field('collection')->find();

            $collectedCount = [
                $articleData['collection'] => [$data['openid'] => ['id' => $id,'collection' => $data['collected']]]
            ];
            foreach ($collectedCount as $key => $value) {
                foreach ($value as $k => $v) {
                    if ($v['collection'] == 'true') {
                        ArticleModel::where('id',$id)->update( ['collection' => $articleData['collection'] + 1] );
                        return json(["code" => 1, "msg" => "收藏成功"]);
                    }
                    if ($v['collection'] == 'false' && $articleData['collection'] > 0) {
                        ArticleModel::where('id',$id)->update( ['collection' => $articleData['collection'] - 1] );
                        return json(["code" => 1, "msg" => "取消收藏成功"]);
                    }
                }
            }
        } else {
            $this->error("id 获取失败");
        }
    }

    /**
     * 增加新闻浏览次数
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function addReading(Request $request)
    {
        $id = $request->param('id');
        $data = ArticleModel::where('id',$id)->setInc('reading');
        return json(["code" => 1, "msg" => "获取成功", "data" => $data]);

//        if ($id = $request->param("id")) {
//            $articleModel = ArticleModel::get($id);    // 获取当前文章所有数据
//            Cache::sAdd("reading".$articleModel["id"]);
//            $count = Cache::sCard("reading".$articleModel["id"]);
//
//            $articleReading = ArticleModel::where('id',$id)->field('reading')->find();
//            ArticleModel::where('id',$id)->update( ['reading' => $articleReading['reading'] + $count] );
//            return json(["code" => 1, "msg" => "增加成功", "data" => $articleReading]);
//        } else {
//            $this->error("id 获取失败");
//        }
    }

    /**
     * 每日新闻头条
     * @return \think\response\Json
     */
    public function getNews()
    {
        // 新闻头条
        $newsData = Cache::get("news");
        if (!$newsData) {
            $api = 'http://v.juhe.cn/toutiao/index';
            $key = '90e4696c8c710d985225c44fa5cdb170';
            $type = 'youxi';

            // get  url请求格式
            $api .= '?key=' . $key;
            $api .= '&type=' . $type;

            // 想要获取接口的数据  其实就是模拟发送get请求  php  curl扩展
            // 初始化
            $curl = curl_init();

            // 设置抓取的url  或者请求接口地址
            curl_setopt($curl,CURLOPT_URL, $api);

            //设置获取的信息以文件流的形式返回，而不是直接输出。
            curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);

            //执行命令  发送请求
            $data = curl_exec($curl);
            $array = json_decode($data, true);

            // 截取6条数据
            $newsData = array_slice($array['result']['data'],0,9);

            $time = time();
            $nowTime = date('H',$time);
            $result = (24 - $nowTime) * 3600;
            Cache::set("news",$newsData,$result);
        }

        return json(['code' => 1, 'data' => $newsData]);
    }
}